package com.tie.jun.ge.xxljob.extenal.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tie.jun.ge.xxljob.config.XxlAdminConfig;
import com.tie.jun.ge.xxljob.extenal.XxlExternalApl;
import com.tie.jun.ge.xxljob.extenal.entity.XxlJobInfo;
import com.tiejun.ge.common.core.domain.R;
import com.tiejun.ge.common.core.exception.module.XxlJobException;
import com.tiejun.ge.common.core.exception.module.enums.XxlJobExceptionEnum;
import com.xxl.job.core.biz.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot
 * @description: 外部接口
 * @author: getiejun
 * @create: 2025-10-19 21:12
 **/

@Component
@Slf4j
public class XxlExternalAplImpl implements XxlExternalApl {

    private static final String TOKEN_KEY = "XXL_JOB_LOGIN_IDENTITY";

    private static String TOKEN = "";

    @Override
    public String getToken() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("userName", XxlAdminConfig.USERNAME);
        requestParam.put("password", XxlAdminConfig.PASSWORD);
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpRequest.post(XxlAdminConfig.LOGIN_URL).form(requestParam).timeout(XxlAdminConfig.CONNECTION_TIME_OUT).execute();
        } catch (Exception e) {
            log.error(">>XxlExternalAplImpl getToken method. the request connection error. login url is:[{}]", XxlAdminConfig.LOGIN_URL, e);
            throw new XxlJobException(XxlJobExceptionEnum.REQUEST_CONNECTION_ERROR);
        }

        if(!httpResponse.isOk()) {
            log.error(">>XxlExternalAplImpl getToken method. user login failed");
            throw new XxlJobException(XxlJobExceptionEnum.USER_LOGIN_FAILED);
        }

        String body = httpResponse.body();
        R result = JSONUtil.toBean(body, R.class);
        if(result.getCode() != 200) {
            log.error(">>XxlExternalAplImpl getToken method. user login failed");
            throw new XxlJobException(XxlJobExceptionEnum.USER_LOGIN_FAILED);
        }
        HttpCookie cookie = httpResponse.getCookie(XxlAdminConfig.COOKIE_NAME);
        return cookie.getValue();
    }

    @Override
    public String add(XxlJobInfo xxlJobInfo) {
        if(StrUtil.isEmpty(TOKEN)) {
            TOKEN = getToken();
        }
        HttpRequest request = HttpRequest.post(XxlAdminConfig.ADD_JOB);
        request.header("Cookie", XxlAdminConfig.COOKIE_NAME + "=" + TOKEN);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(xxlJobInfo));
        HttpResponse response = request.form(jsonObject).timeout(XxlAdminConfig.CONNECTION_TIME_OUT).execute();

        if(response.getStatus() != 200) {
            log.error(">>XxlExternalAplImpl add method. add job error, the request status is:[{}]", response.getStatus());
            throw new XxlJobException(XxlJobExceptionEnum.ADD_JOB_FAILED);
        }
        String body = response.body();
        ReturnT<String> result = JSONUtil.toBean(body, ReturnT.class);
        if(result.getCode() != 200) {
            log.error(">>XxlExternalAplImpl add method. add job error. message is:{}", result.getMsg());
            throw new XxlJobException(XxlJobExceptionEnum.ADD_JOB_FAILED);
        }
        return result.getContent();
    }

    @Override
    public String update(XxlJobInfo xxlJobInfo) {
        return null;
    }

    @Override
    public String remove(XxlJobInfo xxlJobInfo) {
        return null;
    }

    @Override
    public String stop(XxlJobInfo xxlJobInfo) {
        return null;
    }

    @Override
    public String start(XxlJobInfo xxlJobInfo) {
        return null;
    }

    @Override
    public void trigger(XxlJobInfo xxlJobInfo) {
        if(StrUtil.isEmpty(TOKEN)) {
            TOKEN = getToken();
        }
        HttpRequest request = HttpRequest.post(XxlAdminConfig.TRIGGER_JOB);
        request.header("Cookie", XxlAdminConfig.COOKIE_NAME + "=" + TOKEN);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(xxlJobInfo));
        HttpResponse response = request.form(jsonObject).timeout(XxlAdminConfig.CONNECTION_TIME_OUT).execute();

        if(response.getStatus() != 200) {
            log.error(">>XxlExternalAplImpl add method. trigger job error, the request status is:[{}]", response.getStatus());
            throw new XxlJobException(XxlJobExceptionEnum.ADD_JOB_FAILED);
        }
        String body = response.body();
        ReturnT<String> result = JSONUtil.toBean(body, ReturnT.class);
        if(result.getCode() != 200) {
            log.error(">>XxlExternalAplImpl add method. add job error. message is:{}", result.getMsg());
            throw new XxlJobException(XxlJobExceptionEnum.ADD_JOB_FAILED);
        }
    }


}
